Answer:

The listener must coordinate the a button's action command sends with what is done. Copy this program and run it. It is the start for many of the programming exercises for this chapter.

Corrected actionPerformed()

Here is the complete program:

import java.awt.*; 
import java.awt.event.*;
import javax.swing.*; 

public class TwoButtons extends JFrame implements ActionListener
{
  JButton redButton ;
  JButton grnButton ;

  // constructor for TwoButtons
  public TwoButtons()                           
  {
    redButton = new JButton("Red");
    grnButton = new JButton("Green");
    redButton.setActionCommand( "red" );   // set the  command 
    grnButton.setActionCommand( "green" ); // set the  command   

    getContentPane().setLayout( new FlowLayout() ); 
    getContentPane().add( redButton );                      
    getContentPane().add( grnButton );
    
    // register the buttonDemo frame
    // as the listener for both Buttons.
    redButton.addActionListener( this );
    grnButton.addActionListener( this );     

    setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );   
  }

  public void actionPerformed( ActionEvent evt)
  {
    // check which command has been sent
    if ( evt.getActionCommand().equals( "red" ) )
      getContentPane().setBackground( Color.red );    
    else 
      getContentPane().setBackground( Color.green );    

    repaint();
  }

  public static void main ( String[] args )
  {
    TwoButtons demo  = new TwoButtons() ;
    
    demo.setSize( 200, 150 );     
    demo.setVisible( true );      
  }

}

QUESTION 13:

Imagine that you want an icon (a little picture) to appear on each button rather than text. Will this cause problems for actionPerformed()?